<template>
  <el-form
    :model="item"
    ref="formRef"
    :rules="rules"
    style="max-width: 800px"
    label-width="120px"
  >
    <el-form-item label="商品名" prop="itemName">
      <el-input v-model="item.itemName" placeholder="请输入商品名" clearable />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input-number
        :min="0"
        v-model="item.price"
        placeholder="请输入商品价格"
        clearable
      />
    </el-form-item>
    <el-form-item label="描述" prop="desc">
      <el-input
        v-model="item.desc"
        type="textarea"
        placeholder="请输入商品描述"
        clearable
      />
    </el-form-item>
    <el-form-item label="上下架" prop="onsale">
      <el-switch
        v-model="item.onsale"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        :active-value="1"
        :inactive-value="0"
        active-text="上架"
        inactive-text="下架"
        inline-prompt
      />
    </el-form-item>
    <el-form-item label="商品分类" prop="cateId">
      <el-tree-select
        v-model="item.cateId"
        :data="[{ id: 0, cateName: '请选择一个分类' }, ...cates]"
        check-strictly
        :props="{ label: 'cateName', value: 'id' }"
        :render-after-expand="false"
      />
    </el-form-item>
    <el-form-item label="商品图片">
      <el-upload
        action="/api/upload"
        name="file"
        v-model:file-list="fileLists"
        accept=".jpg,.png,.gif,.jpeg"
        list-type="picture-card"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
      >
        <el-button>点击上传</el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品详情">
      <MyEditor
        @editorCreated="editorCreated"
        v-model="item.content"
        :editorConfig="editorConfig"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="formRef.resetFields()">重置</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { Cate } from "@/types/cate";
import type { Item } from "@/types/item";
import { getCates } from "@a/cate";
import { reactive, ref, shallowRef, onMounted } from "vue";
import { ElMessage } from "element-plus";
import MyEditor from "@/components/MyEditor.vue";
import { addItem } from "@a/item";
import { useRouter } from "vue-router";
const router = useRouter();
const rules = {
  itemName: [
    {
      required: true,
      message: "请输入商品名",
      trigger: "blur",
    },
  ],
  price: [
    {
      required: true,
      message: "请输入商品价格",
      trigger: "blur",
    },
  ],
  onsale: [],
  cateId: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === 0) {
          callback(new Error("请选择一个分类"));
        } else {
          callback();
        }
      },
    },
  ],
};
const item = reactive<Item>({
  itemName: "",
  price: 0,
  desc: "",
  onsale: 1,
  pics: [],
  cateId: 0,
  content: "",
});
const formRef = ref<any>(null);

const cates = ref<Cate[]>([]);
const fetchCates = () => {
  getCates().then((res: any) => {
    if (res.code === 200) {
      cates.value = res.data;
    }
  });
};
// 已上传图片
const fileLists = ref<any[]>([]);
onMounted(() => {
  fetchCates();
});
const uploadSuccess = (res: any) => {
  if (res.code === 200) {
    item.pics?.push(res.data);
  }
};
const beforeUpload = (file: any) => {
  if (file.sizes / 1024 / 1024 > 2) {
    ElMessage.error("文件大小不能超过2M");
    return false;
  } else {
    return true;
  }
};

// 接收富文本编辑器实例
const editorRef = shallowRef();
// 富文本编辑器创建完成
const editorCreated = (editor: any) => {
  console.log(editor);
  editorRef.value = editor;
};
const editorConfig = {
  placeholder: "请输入内容",
  MENU_CONF: {
    uploadImage: {
      server: "/api/upload",
      fieldName: "file",
      customInsert(res: any, insertFn: any) {
        if (res.code === 200) {
          insertFn(res.data.url);
        }
      },
    },
  },
};

// 提交表单
const submitForm = () => {
  formRef.value
    .validate()
    .then(() => {
      addItem(item).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: res.msg,
            duration: 1500,
            onClose: () => {
              router.replace("/itemLists");
            },
          });
        }
      });
    })
    .catch(() => {
      ElMessage.error("表单校验失败");
    });
};

defineOptions({
  name: "ItemAdd",
});
</script>

<style scoped></style>
